package com.luoran.bartalks.action;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.luoran.bartalks.action.vo.PlanImplementationVo;
import com.luoran.bartalks.core.UserContext;
import com.luoran.bartalks.entity.biz.BtMateriel;
import com.luoran.bartalks.entity.biz.BtPlanBiz;
import com.luoran.bartalks.entity.biz.BtPlanDetails;
import com.luoran.bartalks.entity.biz.BtPlanEntry;
import com.luoran.bartalks.entity.biz.BtPlanTemplate;
import com.luoran.bartalks.entity.biz.BtProject;
import com.luoran.bartalks.entity.biz.BtProjectMember;
import com.luoran.bartalks.service.IBtProjectReportService;

/**
 * 项目报表
 * 
 * @author wmm 2018年4月18日 下午1:11:30
 */
@Controller
@RequestMapping("/report/project")
public class BtProjectReportAction {
	private static final Logger log = LoggerFactory.getLogger(BtProjectReportAction.class);
	SimpleDateFormat myDateTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	SimpleDateFormat myDateFormat = new SimpleDateFormat("yyyy-MM-dd");

	@Autowired
	private IBtProjectReportService service;

	@RequestMapping
	public String success() {
		log.info("跳转项目报表信息页面");
		return "/reportForm/projectReport";
	}

	/**
	 * 获取项目信息
	 * 
	 * @param number
	 * @return
	 */
	@RequestMapping("/info/{number}")
	@ResponseBody
	public JSONObject getProjectInfo(@PathVariable String number) {
		JSONObject result = new JSONObject();
		int startRow = 0;
		if (!StringUtils.isEmpty(number)) {
			try {
				startRow = Integer.parseInt(number);
			} catch (NumberFormatException e) {
				e.printStackTrace();
				log.info("字符串转整形数字失败");
				result.put("state", false);
				result.put("msg", "系统错误");
				return result;
			}
		}
		List<BtProject> projects = service.queryProjectByCompanyIdofReport(UserContext.get().getCompanyId(), startRow);
		if (projects != null && projects.size() != 0) {
			for (BtProject btProject : projects) {
				// 人员类型(0.管理员,1.成员)
				List<BtProjectMember> managers = service.getProjectMemberByProjectIdAndMembertype(btProject.getId(), 0);
				String managerName = "";
				for (int i = 0; i < managers.size(); i++) {
					if (i == managers.size() - 1) {
						managerName = managerName + managers.get(i).getMemberName();
					} else {
						managerName = managerName + managers.get(i).getMemberName() + " , ";
					}
				}
				btProject.setManagerName(managerName);
				List<BtProjectMember> members = service.getProjectMemberByProjectIdAndMembertype(btProject.getId(), 1);
				String memberrName = "";
				for (int i = 0; i < members.size(); i++) {
					if (i == members.size() - 1) {
						memberrName = memberrName + members.get(i).getMemberName();
					} else {
						memberrName = memberrName + members.get(i).getMemberName() + " , ";
					}
				}
				btProject.setMemberName(memberrName);
				btProject.setCreateDateStr(myDateTimeFormat.format(btProject.getCreateDate()));
			}
			result.put("state", true);
			result.put("list", projects);
		} else {
			result.put("state", true);
			result.put("list", null);
		}
		return result;
	}

	/**
	 * 根据项目id获取计划信息
	 * 
	 * @param number
	 * @return
	 */
	@RequestMapping("/plan/title/{number}")
	@ResponseBody
	public JSONObject getPlanTitle(@PathVariable String number,
			@RequestParam(value = "projectId", required = false) String projectId) {
		JSONObject result = new JSONObject();
		int startRow = 0;
		if (!StringUtils.isEmpty(number)) {
			try {
				startRow = Integer.parseInt(number);
			} catch (NumberFormatException e) {
				e.printStackTrace();
				log.info("字符串转整形数字失败");
				result.put("state", false);
				result.put("msg", "系统错误");
				return result;
			}
		}
		List<BtPlanDetails> planDetails = service.queryPlanByProjectIdOfReport(projectId, startRow);
		if (planDetails != null && planDetails.size() != 0) {
			result.put("state", true);
			result.put("list", planDetails);
		} else {
			result.put("state", true);
			result.put("list", null);
		}
		return result;
	}

	/**
	 * 获取计划信息
	 * 
	 * @param projectid
	 * @return
	 */
	@RequestMapping("/plan/info/{planId}")
	@ResponseBody
	public JSONObject getPlanInfo(@PathVariable String planId) {
		JSONObject result = new JSONObject();
		PlanImplementationVo planImplementation = new PlanImplementationVo();
		BtPlanDetails planDetails = service.getPlanInfoByIdOfReport(planId);
		if (planDetails != null) {
			planImplementation.setPlanId(planDetails.getId());
			planImplementation.setRemark(planDetails.getRemark());
			planImplementation.setStatus(planDetails.getStatus());
			planImplementation.setTransportTypeName(planDetails.getTransportTypeName());
			planImplementation.setDistance(planDetails.getDistance());
			planImplementation.setStartDateStr(myDateFormat.format(planDetails.getStartDate()));
			planImplementation.setEndDateStr(myDateFormat.format(planDetails.getEndDate()));
			planImplementation.setStartPlaceName(planDetails.getStartPlaceName());
			planImplementation.setDestinationName(planDetails.getDestinationName());
			planImplementation.setCreateTimeStr(myDateTimeFormat.format(planDetails.getCreateTime()));
			planImplementation.setWeekPolicy(planDetails.getWeekPolicy());
			planImplementation.setHolidayPolicy(planDetails.getHolidayPolicy());
			BtPlanTemplate templateNameById = service.getTemplateNameById(planDetails.getTemplateId());
			if (templateNameById == null) {
				planImplementation.setTemplateName("模版信息丢失!");
			} else {
				planImplementation.setTemplateName(templateNameById.getPlanTemplateName());
			}
			if (planDetails.getStatus() == 4) {
				planImplementation.setHasException(1);
			} else {
				planImplementation.setHasException(0);
			}
			List<BtPlanEntry> planEntrys = service.getPlanEntryByPlanIdOfReport(planDetails.getId());
			// 如果此地点有装卸货业务则为到达该地点,如果此地点的装卸货容器有运输容器则视为已经出发
			if (planEntrys != null && planEntrys.size() != 0) {
				for (BtPlanEntry btPlanEntry : planEntrys) {
					List<BtPlanBiz> findArrive = service.findArrive(planDetails.getProjectId(), planDetails.getId(),
							btPlanEntry.getId());
					if (findArrive != null && findArrive.size() != 0) {
						for (BtPlanBiz btPlanBiz : findArrive) {
							if (service.findContainerTypeById(btPlanBiz.getContainerId()).getContainerType() != 1) {
								btPlanEntry.setArrive(1);
								break;
							} else {
								btPlanEntry.setArrive(2);
							}
						}
					} else {
						btPlanEntry.setArrive(0);
					}
				}
				planImplementation.setPlanEntry(planEntrys);
			} else {
				planImplementation.setPlanEntry(null);
			}
			result.put("state", true);
			result.put("obj", planImplementation);
		} else {
			result.put("state", true);
			result.put("obj", null);
		}
		return result;
	}

	/**
	 * 根据计划id获取物料信息
	 * 
	 * @param number
	 * @return
	 */
	@RequestMapping("/plan/materiel/{number}")
	@ResponseBody
	public JSONObject getMaterielList(@PathVariable String number,
			@RequestParam(value = "planEntryId", required = false) String planEntryId,
			@RequestParam(value = "type", required = false) String type) {
		JSONObject result = new JSONObject();
		int startRow = 0;
		if (!StringUtils.isEmpty(number)) {
			try {
				startRow = Integer.parseInt(number);
			} catch (NumberFormatException e) {
				e.printStackTrace();
				log.info("字符串转整形数字失败");
				result.put("state", false);
				result.put("msg", "系统错误");
				return result;
			}
		}
		List<BtMateriel> materiel = service.getMaterielByPlanEntryIdOfReport(planEntryId, startRow, type);
		if (materiel != null && materiel.size() != 0) {
			if("1".equals(type)) {
				try {
					BtPlanEntry planEntry = service.getPlanEntryById(planEntryId);
					BtPlanEntry planEntryBySign = service.getPlanEntryByPlanIdAndSign(planEntry.getPlanId(), UserContext.get().getCompanyId(), planEntry.getSign()+1);
					for (BtMateriel btMateriel : materiel) {
						btMateriel.setBeAddressName("在从"+planEntry.getAddressName()+"前往"+planEntryBySign.getAddressName()+"的途中");
					}
				} catch (Exception e) {
					e.printStackTrace();
					log.info("type参数为1时查验其他信息出错");
					result.put("state", false);
					result.put("msg", "系统错误");
					return result;
				}
			}
			result.put("state", true);
			result.put("list", materiel);
		} else {
			result.put("state", true);
			result.put("list", null);
		}
		return result;
	}

	/**
	 * 查看异常
	 * 
	 * @param planId
	 * @return
	 */
	@RequestMapping("/plan/exception/{planId}")
	@ResponseBody
	public JSONObject getException(@PathVariable String planId) {
		JSONObject result = new JSONObject();
		List<String> infolist = new ArrayList<String>();
		List<BtPlanEntry> planEntryException = service.getPlanEntryException(planId);
		if (!planEntryException.isEmpty() || planEntryException == null) {
			for (BtPlanEntry btPlanEntry : planEntryException) {
				if (btPlanEntry.getStates() == 1) {
					String enumTypeValue = btPlanEntry.getException();
				    if(StringUtils.isEmpty(enumTypeValue)) {
				    	enumTypeValue="未知";
				    }
					String exceptionInfo = "在地点: " + btPlanEntry.getAddressName() + "  发生的异常信息为: "
							+ enumTypeValue+ "。";
					infolist.add(exceptionInfo);
				}
			}
			result.put("state", true);
			result.put("data", infolist);
		} else {
			result.put("state", false);
			result.put("msg", "系统错误,请刷新页面再试");
		}
		return result;
	}

}
